import { observable, action } from "mobx-miniprogram"
import { getStorage, removeStorage, setStorage } from "../utils/storage"
import { fetchUserInfoAPI, loginAPI } from "../api/userAPI"
import { UserInfo } from "../type/userTypes"

const userStore = observable({
  token: getStorage<string>("token") || "",
  userInfo: getStorage<UserInfo>("userInfo") || {} as UserInfo,
  /**
   * @description 登录的action
   */
  login: action(() => {
    wx.login({
      success: async (result: WechatMiniprogram.LoginSuccessCallbackResult) => {
        if (result.code) {
          try {
            const { data: { data: { token } } } = await loginAPI(result.code)
            setStorage<string>("token", token)
            userStore.setToken(token)
            userStore.fetchuserInfo()
            wx.reLaunch({
              url: "/pages/user/user"
            })
          } catch (error) {
            wx.showToast({ icon: "error", title: error.message })
          }
        } else {
          wx.showToast({ icon: "error", title: "授权失败重新授权" })
        }
      },
      fail: () => {
        wx.showToast({ icon: "error", title: "用户授权失败" })
      }
    })
  }),

  /**
 * @description 获取用户信息的action
 */
  fetchuserInfo: action(async () => {
    const { data: { data } } = await fetchUserInfoAPI()
    setStorage<UserInfo>("userInfo", data)
    userStore.userInfo = data
  }),

  /**
 * @description 存储token的action
 */
  setToken: action((token: string) => {
    userStore.token = token
  }),

  /**
   * @description 移除token的action
   */
  removeToken: action(() => {
    userStore.token = ""
    removeStorage("token")
  })
})

export default userStore